<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <title>文件传输</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            background-color: #1e1e1e;
            color: #ffffff;
            font-family: Arial, sans-serif;
        }
        .container {
            display: flex;
            flex-direction: column;
            height: 100vh;
        }
        .header {
            padding: 10px 20px;
            background-color: #2d2d2d;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .chat-area {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
        }
        .input-area {
            padding: 20px;
            background-color: #2d2d2d;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .file-input {
            display: none;
        }
        .upload-btn {
            padding: 8px 15px;
            background-color: #4CAF50;
            border: none;
            color: white;
            cursor: pointer;
            border-radius: 4px;
        }
        .send-btn {
            padding: 8px 15px;
            background-color: #2196F3;
            border: none;
            color: white;
            cursor: pointer;
            border-radius: 4px;
        }
        .file-item {
            padding: 10px;
            margin: 5px 0;
            background-color: #2d2d2d;
            border-radius: 4px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .download-btn {
            padding: 5px 10px;
            background-color: #4CAF50;
            border: none;
            color: white;
            cursor: pointer;
            border-radius: 4px;
        }
        .main-container {
            display: flex;
            flex: 1;
        }
        .chat-container {
            flex: 1;
            display: flex;
            flex-direction: column;
        }
        .online-users {
            width: 200px;
            background-color: #2d2d2d;
            padding: 20px;
            border-left: 1px solid #3d3d3d;
            overflow-y: auto;
        }
        .online-users h3 {
            margin: 0 0 15px 0;
            color: #ffffff;
            font-size: 16px;
        }
        .user-item {
            padding: 8px 12px;
            margin: 5px 0;
            background-color: #363636;
            border-radius: 4px;
            color: #ffffff;
        }
        .user-item.self {
            background-color: #1e88e5;
        }
        .user-ip {
            font-size: 14px;
            color: #ffffff;
        }
        .message-input-area {
            padding: 20px;
            background-color: #2d2d2d;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .message-input {
            flex: 1;
            padding: 8px;
            background-color: #363636;
            border: none;
            border-radius: 4px;
            color: #ffffff;
            font-size: 14px;
            resize: none;
            min-height: 20px;
            max-height: 100px;
        }
        .message-input:focus {
            outline: none;
            background-color: #404040;
        }
        .message-item {
            padding: 12px;
            margin: 8px 0;
            background-color: #2d2d2d;
            border-radius: 8px;
            max-width: 80%;
        }
        .message-item.self {
            background-color: #1e88e5;
            margin-left: auto;
        }
        .message-header {
            font-size: 12px;
            color: rgba(255, 255, 255, 0.6);
            margin-bottom: 4px;
        }
        .message-content {
            color: #ffffff;
            word-break: break-word;
            line-height: 1.4;
        }
        .message-image {
            max-width: 100%;
            max-height: 300px;
            border-radius: 4px;
            margin-top: 5px;
        }
        .file-actions {
            display: flex;
            gap: 10px;
            margin-top: 10px;
        }
        .file-info {
            display: flex;
            flex-direction: column;
            gap: 4px;
        }
        .file-name {
            font-weight: bold;
        }
        .file-size {
            font-size: 12px;
            color: rgba(255, 255, 255, 0.7);
        }
        
        /* 添加响应式样式 */
        @media screen and (max-width: 768px) {
            .main-container {
                flex-direction: column;
            }
            
            .online-users {
                width: 100%;
                height: 120px;
                border-left: none;
                border-top: 1px solid #3d3d3d;
                padding: 10px;
            }
            
            .online-users h3 {
                margin-bottom: 8px;
            }
            
            .user-item {
                display: inline-block;
                margin-right: 8px;
                padding: 6px 10px;
            }
            
            .user-ip {
                font-size: 12px;
            }
            
            .message-item {
                max-width: 90%;
            }
            
            .message-input-area {
                padding: 10px;
                gap: 6px;
            }
            
            .message-input {
                font-size: 16px; /* 防止iOS自动缩放 */
                padding: 6px;
            }
            
            .upload-btn, .send-btn {
                padding: 6px 10px;
                font-size: 14px;
                min-width: 60px;
            }
            
            .header {
                padding: 8px 10px;
                font-size: 14px;
            }
            
            .chat-area {
                padding: 10px;
            }
            
            /* 文件项目样式调整 */
            .file-item {
                flex-direction: column;
                gap: 8px;
                align-items: flex-start;
            }
            
            .file-item .download-btn {
                align-self: flex-end;
            }
            
            /* 图片大小限制 */
            .message-image {
                max-height: 200px;
            }
        }
        
        /* 添加安全区域适配（适配刘海屏） */
        @supports (padding-top: env(safe-area-inset-top)) {
            .container {
                padding-top: env(safe-area-inset-top);
                padding-bottom: env(safe-area-inset-bottom);
            }
            
            .header {
                padding-top: max(8px, env(safe-area-inset-top));
            }
            
            .message-input-area {
                padding-bottom: max(10px, env(safe-area-inset-bottom));
            }
        }
        
        /* 优化触摸体验 */
        @media (hover: none) and (pointer: coarse) {
            .upload-btn, .send-btn, .download-btn {
                min-height: 36px; /* 更容易点击 */
            }
            
            .user-item {
                padding: 8px 12px; /* 更容易点击 */
            }
            
            /* 防止双击缩放 */
            .message-content {
                touch-action: manipulation;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <span id="device-id">设备ID: </span>
            <span id="online-status">在线</span>
        </div>
        <div class="main-container">
            <div class="chat-container">
                <div class="chat-area" id="chat-area">
                    <!-- 消息将在这里显示 -->
                </div>
                <div class="message-input-area">
                    <textarea 
                        class="message-input" 
                        id="message-input"
                        placeholder="输入消息或粘贴图片..."
                        rows="1"
                    ></textarea>
                    <input type="file" id="file-input" class="file-input" multiple>
                    <button onclick="document.getElementById('file-input').click()" class="upload-btn">
                        选择文件
                    </button>
                    <button class="send-btn" id="send-btn">发送</button>
                </div>
            </div>
            <div class="online-users">
                <h3>在线用户</h3>
                <div id="users-list">
                    <!-- 在线用户列表将在这里显示 -->
                </div>
            </div>
        </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.5.0/sockjs.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
    <script>
        const deviceId = Math.random().toString(36).substr(2, 9);
        document.getElementById('device-id').textContent = `设备ID: ${deviceId}`;
        
        // WebSocket连接
        const socket = new SockJS('/ws');
        const stompClient = Stomp.over(socket);
        
        // 禁用 STOMP 的调试日志
        stompClient.debug = null;
        
        let onlineUsers = new Map();

        stompClient.connect({}, function(frame) {
            console.log('WebSocket连接成功');
            
            // 订阅文件消息
            stompClient.subscribe('/topic/files', function(message) {
                console.log('收到新文件消息:', message.body);
                const fileInfo = JSON.parse(message.body);
                if (fileInfo.deviceId !== deviceId) {
                    console.log('显示新文件:', fileInfo);
                    addFileItem(fileInfo);
                } else {
                    console.log('忽略自己发送的文件');
                }
            });

            // 订阅用户状态消息
            stompClient.subscribe('/topic/users', function(message) {
                const update = JSON.parse(message.body);
                handleUsersUpdate(update);
            });

            // 订阅消息主题
            stompClient.subscribe('/topic/messages', function(message) {
                const messageInfo = JSON.parse(message.body);
                if (messageInfo.deviceId !== deviceId) {
                    addMessageItem(messageInfo);
                }
            });

            // 发送用户上线消息
            stompClient.send("/app/user.connect", {}, JSON.stringify({
                deviceId: deviceId,
                status: 'ONLINE'
            }));
        }, function(error) {
            console.error('WebSocket连接失败:', error);
        });
        
        document.getElementById('file-input').addEventListener('change', function(e) {
            const files = e.target.files;
            if (files.length > 0) {
                document.getElementById('send-btn').textContent = `发送 (${files.length} 个文件)`;
            }
        });

        document.getElementById('send-btn').addEventListener('click', function() {
            const text = document.getElementById('message-input').value.trim();
            const files = document.getElementById('file-input').files;
            
            if (text) {
                const messageInfo = {
                    type: 'TEXT',
                    content: text,
                    deviceId: deviceId,
                    timestamp: new Date().getTime()
                };
                // 发送消息
                sendTextMessage(messageInfo);
                // 立即在本地显示消息
                addMessageItem(messageInfo);
                // 清空输入框
                document.getElementById('message-input').value = '';
                // 重置输入框高度
                document.getElementById('message-input').style.height = 'auto';
            }
            
            if (files.length > 0) {
                sendFiles(files);
                document.getElementById('file-input').value = '';
            }
        });

        function addFileItem(fileInfo) {
            const chatArea = document.getElementById('chat-area');
            const fileItem = document.createElement('div');
            fileItem.className = 'file-item';
            
            const fileDetails = document.createElement('div');
            fileDetails.textContent = `${fileInfo.fileName} (${formatFileSize(fileInfo.fileSize)})`;
            
            const downloadBtn = document.createElement('button');
            downloadBtn.className = 'download-btn';
            downloadBtn.textContent = '下载';
            downloadBtn.onclick = () => window.location.href = `/api/download/${fileInfo.fileId}`;
            
            fileItem.appendChild(fileDetails);
            fileItem.appendChild(downloadBtn);
            chatArea.appendChild(fileItem);
            chatArea.scrollTop = chatArea.scrollHeight;
        }

        function formatFileSize(bytes) {
            if (bytes < 1024) return bytes + ' B';
            if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB';
            if (bytes < 1024 * 1024 * 1024) return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
            return (bytes / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
        }

        // 更新用户列表显示
        function updateUsersList() {
            const usersList = document.getElementById('users-list');
            usersList.innerHTML = '';
            
            onlineUsers.forEach(user => {
                const userItem = document.createElement('div');
                userItem.className = `user-item${user.deviceId === deviceId ? ' self' : ''}`;
                userItem.innerHTML = `
                    <div class="user-ip">${user.deviceId === deviceId ? '我' : user.ipAddress || '未知'}</div>
                `;
                usersList.appendChild(userItem);
            });
        }

        // 修改处理用户列表更新的函数
        function handleUsersUpdate(update) {
            console.log('收到用户列表更新:', update); // 添加日志
            onlineUsers.clear();
            if (update && update.users) {
                update.users.forEach(user => {
                    onlineUsers.set(user.deviceId, user);
                });
            }
            updateUsersList();
        }

        // 添加消息到聊天区域
        function addMessageItem(messageInfo) {
            const chatArea = document.getElementById('chat-area');
            const messageItem = document.createElement('div');
            messageItem.className = `message-item${messageInfo.deviceId === deviceId ? ' self' : ''}`;
            
            const header = document.createElement('div');
            header.className = 'message-header';
            header.textContent = `设备 ${messageInfo.deviceId} · ${new Date(messageInfo.timestamp).toLocaleTimeString()}`;
            
            const content = document.createElement('div');
            content.className = 'message-content';
            
            if (messageInfo.type === 'TEXT') {
                content.textContent = messageInfo.content;
            } else if (messageInfo.type === 'IMAGE') {
                const img = document.createElement('img');
                img.src = messageInfo.content;
                img.className = 'message-image';
                content.appendChild(img);
            }
            
            messageItem.appendChild(header);
            messageItem.appendChild(content);
            chatArea.appendChild(messageItem);
            chatArea.scrollTop = chatArea.scrollHeight;
        }

        // 修改发送文本消息的函数
        function sendTextMessage(messageInfo) {
            stompClient.send("/app/message", {}, JSON.stringify(messageInfo));
        }

        // 发送图片
        function sendImage(file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                stompClient.send("/app/message", {}, JSON.stringify({
                    type: 'IMAGE',
                    content: e.target.result,
                    deviceId: deviceId,
                    timestamp: new Date().getTime()
                }));
            };
            reader.readAsDataURL(file);
        }

        // 自动调整输入框高度
        const messageInput = document.getElementById('message-input');
        
        messageInput.addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = (this.scrollHeight) + 'px';
        });

        // 处理粘贴事件
        messageInput.addEventListener('paste', function(e) {
            const items = e.clipboardData.items;
            for (let item of items) {
                if (item.type.indexOf('image') !== -1) {
                    e.preventDefault();
                    const file = item.getAsFile();
                    sendImage(file);
                    return;
                }
            }
        });

        // 修改发送文件函数
        function sendFiles(files) {
            const formData = new FormData();
            for (let file of files) {
                formData.append('files', file);
                console.log('添加文件到表单:', file.name, file.size);
            }
            formData.append('deviceId', deviceId);

            console.log('开始上传文件...');
            fetch('/api/upload', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (response.ok) {
                    console.log('文件上传成功');
                    document.getElementById('file-input').value = '';
                    document.getElementById('send-btn').textContent = '发送';
                } else {
                    console.error('文件上传失败:', response.statusText);
                }
            })
            .catch(error => {
                console.error('上传出错:', error);
            });
        }

        // 页面关闭时发送离线消息
        window.addEventListener('beforeunload', function() {
            if (stompClient && stompClient.connected) {
                stompClient.send("/app/user.disconnect", {}, JSON.stringify({
                    deviceId: deviceId,
                    status: 'OFFLINE'
                }));
            }
        });
    </script>
</body>
</html>